package org.ala.tcp_feign_server.handler.login;

import org.ala.tcp_feign_common.config.AttrbuteKeyNamespace;
import org.ala.tcp_feign_common.enums.TcpFeignCloseTypeEnums;
import org.ala.tcp_feign_common.enums.TcpFeignMessageTypeEnums;
import org.ala.tcp_feign_common.handler.IByteMessageAction;
import org.ala.tcp_feign_common.logs.LoggerFactory;
import org.ala.tcp_feign_common.msg.login.LoginACKByteMessage;
import org.ala.tcp_feign_common.msg.login.LoginByteMessage;
import org.ala.tcp_feign_server.context.TcpFeignServerContext;
import org.slf4j.Logger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;


/**
 * 登录消息
 * <p>	客户端 -> 服务端
 *
 * @author 骆毅(ala)
 * @date 2024年4月19日
 */
public class LoginByteMessageAction implements IByteMessageAction<LoginByteMessage> {
	
	
	static Logger log = LoggerFactory.getLogger("tcp-feign", "server");
	

	@Override
	public TcpFeignMessageTypeEnums type() {
		return TcpFeignMessageTypeEnums.LOGIN;
	}

	@Override
	public void action(ChannelHandlerContext ctx, LoginByteMessage msg) {
		log.info("[LoginByteMessageAction action] 收到登录消息 " +
									" remoteAddress:" + ctx.channel().remoteAddress() + 
									" username:" + msg.getUserName() + " password:" + msg.getPassword());
		
		//	验证登录消息
		String username = msg.getUserName();
		String password = msg.getPassword();
		
		String configUsername = TcpFeignServerContext.instance().getConfig().getUsername();
		String configPassword = TcpFeignServerContext.instance().getConfig().getPassword();
		
		if (configUsername == null || configPassword == null) {
			renderSuccess(ctx);
		} else if (!configUsername.equals(username) || !configPassword.equals(password)) {
			renderFaild(ctx);
		} else {
			renderSuccess(ctx);
		}
	}
	/**
	 * 登录成功
	 */
	protected void renderSuccess(ChannelHandlerContext ctx) {
		ctx.channel().attr(AttributeKey.valueOf(AttrbuteKeyNamespace.LOGIN)).set(true);
		ctx.channel().writeAndFlush(LoginACKByteMessage.success());
		
		log.info("[LoginByteMessageAction action] 客户端登录成功 remoteAddress:" + ctx.channel().remoteAddress());
	}
	/**
	 * 登录失败
	 */
	protected void renderFaild(ChannelHandlerContext ctx) {
		ctx.channel().writeAndFlush(LoginACKByteMessage.faild());
		TcpFeignServerContext.instance().closeClient(ctx.channel(), TcpFeignCloseTypeEnums.LOGIN_ERROR);
		
		log.info("[LoginByteMessageAction action] 客户端登录失败 remoteAddress:" + ctx.channel().remoteAddress());
	}

}
